package com.syh.bscommon.interceptor;

import com.syh.bscommon.Util.JwtUtils;
import com.syh.bscommon.Util.UserHolder;
import com.syh.bscommon.pojo.UserInfo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginCheckInterceptor {

    public Mono<Boolean> preHandle(ServerWebExchange exchange) {
        String tokens = exchange.getRequest().getHeaders().getFirst("authorization");
        if (tokens == null || tokens.isEmpty()) {
            log.info("token不存在");
            return Mono.just(false);
        }
        String token = tokens.startsWith("Bearer ") ? tokens.substring(7) : tokens;
        log.info("token:" + token);

        try {
            Claims claims = JwtUtils.parseJWT(token);
            if (claims == null) {
                log.info("解析失败，claims为空");
                return Mono.just(false);
            }
            String email = claims.get("email", String.class);
            log.info("email: " + email);

            String status = claims.get("lockUser", String.class);
            if ("0".equals(status)) {
                log.info("用户被禁用");
                return Mono.just(false);
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setEmail(email);
            userInfo.setCompanyId(claims.get("companyId", Integer.class));
            userInfo.setId(claims.get("id", Integer.class));
            UserHolder.saveUser(userInfo);
        } catch (Exception e) {
            log.info("请求头不正确!!");
            return Mono.just(false);
        }
        return Mono.just(true)
                .doFinally(signalType -> {
                    log.info("请求完成后释放资源");
                    UserHolder.removeUser(); // 请求完成后释放资源
                });
    }
}
